package org.apache.ocean;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.MergePolicy;
import org.apache.lucene.index.StaleReaderException;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.LockObtainFailedException;


public class RamIndex extends ClusterIndexModifier {
  private boolean recordDeletes = false;
  private boolean stopDeletes = false;
  private boolean stopAdds = false;
  ConcurrentLinkedQueue<Term> queuedDeletedTerms = new ConcurrentLinkedQueue<Term>();
  
  public RamIndex(CDouble ramBufferSize, MergePolicy mergePolicy, Directory directory, Analyzer analyzer) throws CorruptIndexException, IOException {
  	super(ramBufferSize, mergePolicy, directory, analyzer);
  }
  
  public void stopDeletes() {
  	stopDeletes = true;
  }
  
  public void recordDeletes() {
  	recordDeletes = true;
  }
  
  public List<Term> getQueuedDeletedTerms() {
  	return new ArrayList<Term>(queuedDeletedTerms);
  }
  
  public CLong deleteDocuments(Term term, boolean reloadBeforeDelete, boolean flush, boolean reloadAfterFlush) throws StaleReaderException, CorruptIndexException, LockObtainFailedException, IOException, Exception {
  	errorIfClosed();
  	if (stopDeletes) {
  		throw new Exception("not allowing anymore deletes");
  	}
  	if (recordDeletes) {
  		queuedDeletedTerms.add(term);
  	}
  	return super.deleteDocuments(term, reloadBeforeDelete, flush, reloadAfterFlush);
  }
  
  public void addDocuments(List<Document> documents, Analyzer analyzer, boolean flush) throws CorruptIndexException, IOException, InterruptedException, Exception {
  	errorIfClosed();
  	if (recordDeletes) throw new Exception("only allowing deletes");
  	super.addDocuments(documents, analyzer, flush);
	}
  
  public void addDocument(Document document, Analyzer analyzer, boolean flush) throws CorruptIndexException, IOException, InterruptedException, Exception {
  	errorIfClosed();
  	if (recordDeletes) throw new Exception("only allowing deletes");
  	super.addDocument(document, analyzer, flush);
  }
}
